package com.work.tz.service.impl;

import com.work.tz.mapper.MenuMapper;
import com.work.tz.model.Menu;
import com.work.tz.model.TPerson;
import com.work.tz.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MenuServiceImpl implements MenuService {



    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Map<String, Object>> getMenu2RolePerson(TPerson person) {
        List<Menu> menuList = menuMapper.getMenu2RolePerson(person.getPid());
        return get(menuList,0);
    }

    @Override
    public List<Menu> getMenu2RolePerson2(TPerson person) {
        return menuMapper.getMenu2RolePerson(person.getPid());
    }


    private List<Map<String, Object>> get(List<Menu> menuList,Integer pid){
        List<Map<String, Object>> mapList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(menuList)){
            for (Menu menu : menuList) {
                Map<String, Object> map = null;
                if(pid == menu.getParentid()){
                    map = new HashMap<>();
                    map.put("id",menu.getId());
                    map.put("text",menu.getText());
                    map.put("url",menu.getUrl());
                    map.put("nodes",get(menuList,menu.getId()));
                    if(!CollectionUtils.isEmpty(map)){
                        List<Map<String, Object>> nodes = (List<Map<String, Object>>) map.get("nodes");
                        if(nodes.size() <= 0){
                            map.remove("nodes");
                        }
                        mapList.add(map);
                    }

                }
            }
        }
        return mapList;
    }
}
